What is the difference between the first and single functions in LINQ?
What is the difference between the first and single functions in LINQ?
680
24-Sep-2021
Ravi Vishwakarma
27-Sep-2021First and Single operator difference
First
Single
Example
using System; using System.Collections.Generic; using System.Linq; public class Program { public static void Main() { List<Student> students = new List<Student>(){ new Student() { StudentId = 1, Name = 'Ashu', Marks = 500 }, new Student() { StudentId = 2, Name = 'Shyam', Marks = 300 }, new Student() { StudentId = 3, Name = 'Shriyam', Marks = 400 }, new Student() { StudentId = 4, Name = 'Sunny', Marks = 550 }, new Student() { StudentId = 5, Name = 'Ram', Marks = 600 }, new Student() { StudentId = 6, Name = 'Krishna', Marks = 700 }, new Student() { StudentId = 7, Name = 'Anupam', Marks = 550 } } ;Student first = students.First(); Console.WriteLine('\nFirst() :\n'); Console.WriteLine('{0,-10} {1,10} {2,5}','Name', 'ID', 'Marks'); Console.WriteLine('{0,-10} {1,10} {2,5}', first.Name, first.StudentId, first.Marks); // Student first = students.Where( stu => stu.Marks > 500).Single(); // this will throw an InvalidOperationException exception because more than 1 element in students. Student last = students.Single( stu => stu.StudentId == 2); Console.WriteLine('\nSingle() :\n'); Console.WriteLine('{0,-10} {1,10} {2,5}','Name', 'ID', 'Marks'); Console.WriteLine('{0,-10} {1,10} {2,5}', last.Name, last.StudentId, last.Marks); Console.ReadLine(); } } class Student { public int StudentId { get; set; } public string Name { get; set; } public int Marks { get; set; } }
Output